<?php defined('LIBRARY') or die('No direct script access.');
 final class dir{
    /**
     * Stores the directory tree
     *
     * @var array
     */
    public $dir_tree;
    public $ext_img;

    /**
     * Class constructor. Takes as parameter the top directory path that will be read
     *
     * @param string $path_to_dir
     */
    function __construct() {
        $this->ext_img=array("jpg", "gif", "png");
    }

    /**
     * Reads the main directory and all subsequent directories inside the given path.
     * The tree is stored in $dir_tree
     *
     * @param string $directory
     */
    function read_directory($directory) {
        if ($handle = @opendir($directory)) {
            while (false !== ( $file = readdir($handle) )) {
                if ($file != ".." && $file != ".") {
                    if (is_dir($directory . '/' . $file)) {
                        $this->dir_tree['directories'][] = $directory . '/' . $file;
                        $this->read_directory($directory . '/' . $file);
                    }
                    else {
                        $this->dir_tree['files'][] = $directory . '/' . $file;
                    }
                }
            }
            $data=$this->dir_tree;
            unset ($this->dir_tree);
            return $data;
        }
    }

    function read_directory_image($directory) {
        if ($handle = @opendir($directory)) {
            while (false !== ( $file = readdir($handle) )) {
                if ($file != ".." && $file != ".") {
                    if (is_dir($directory . '/' . $file)) {
                        $this->dir_tree['directories'][] = $directory . '/' . $file;
                        $this->read_directory($directory . '/' . $file);
                    }
                    else {
                        $ext=substr($file,strrpos($file, ".")+1);
                        if(in_array($ext,$this->ext_img)) {
                            $this->dir_tree['files'][] =$file;
                        }
                    }
                }
            }
            $data=$this->dir_tree;
            unset ($this->dir_tree);
            return $data;
        }
    }

    /**
     * Deletes all the directories and files stored inside $dir_tree
     *
     */
    function delete_directory() {
        if (is_array($this->dir_tree['files'])) {
            foreach ($this->dir_tree['files'] as $value)
                @unlink($value);
        }
        if (is_array($this->dir_tree['directories'])) {
            $this->dir_tree['directories'] = array_reverse($this->dir_tree['directories']);
            foreach ($this->dir_tree['directories'] as $value)
                @rmdir($value);
        }
    }

}